package com.project.nimsen.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Repository;

import com.project.jdbc.dao.IBaseJdbcDao;
import com.project.jdbc.service.BaseServiceImpl;
import com.project.jdbc.utils.Finder;
import com.project.nimsen.common.constant.ComBillSrcType;
import com.project.nimsen.common.constant.UnitConstant;
import com.project.nimsen.dao.IBaseDao;
import com.project.nimsen.dto.BComBillDto;
import com.project.nimsen.entity.BActionBillEntity;
import com.project.nimsen.entity.BCirBillEntity;
import com.project.nimsen.entity.BComBillEntity;
import com.project.nimsen.entity.BExamineBillEntity;
import com.project.nimsen.entity.SUnitsEntity;
import com.project.nimsen.entity.TAnswerBillEntity;
import com.project.nimsen.service.IBComBillService;
import com.project.nimsen.service.ISUnitsService;
@Repository("bComBillService")
public class BComBillServiceImpl extends BaseServiceImpl implements
		IBComBillService {
	@Resource
	IBaseDao baseDao;
	@Resource
	ISUnitsService unitsService;
	protected IBaseJdbcDao getBaseDao() {
		return baseDao;
	}
	public boolean saveByDto(BComBillDto dto) throws Exception {
		if(dto==null)
			return false;
		Date now = new Date();
		//添加一个单据
		if(StringUtils.isBlank(dto.getBill_id())){
			if(!saveComBillByDto(dto, now))
				return false;
		}
		//如果不是第一次流转，测把之前的流转单改为已办
		if(StringUtils.isNotBlank(dto.getCir_bill_id())){
			if(!updateReadById(dto.getCir_bill_id()))
				return false;
		}
		//当有答复单时候的处理
		if(StringUtils.isNotBlank(dto.getExa_bill_id())){
			TAnswerBillEntity answer_bill = new TAnswerBillEntity();
			answer_bill.setAnswer_time(now);
			answer_bill.setCir_id(dto.getCir_bill_id());
			answer_bill.setAnswer_user_id(dto.getUserid());
			answer_bill.setExamine_id(dto.getExa_bill_id());
			answer_bill.setSatisfy(Integer.parseInt(dto.getSatisfy()));
			answer_bill.setRemark(dto.getRemark());
			Object obj_id = baseDao.saveEntity(answer_bill);
			if(obj_id==null)
				return false;
			//更投诉单状态
			String bill_id = dto.getBill_id();
			Finder finder = new Finder("update B_COM_BILL set active=2 where id=:id");
			finder.setParam("id", bill_id);
			return baseDao.update(finder)>0;
		}
		BCirBillEntity bCir_Bill = new BCirBillEntity();
		bCir_Bill.setActive(0);
		bCir_Bill.setActive_user_id(dto.getUserid());
		bCir_Bill.setBill_id(dto.getBill_id());
		bCir_Bill.setBill_time(now);
		String src_unitid=dto.getUnitid();
		bCir_Bill.setSrc_unit_id(src_unitid);
		//当来源部门是客服部的时候
		if(UnitConstant.CUSTOMER_SERVICE.equals(src_unitid)){
			bCir_Bill.setCir_unit_id(UnitConstant.OFFICE);
			return baseDao.saveEntity(bCir_Bill)!=null;
		}
		//当来源部门是办公室的时候
		if(UnitConstant.OFFICE.equals(src_unitid)){
			bCir_Bill.setCir_unit_id(dto.getCir_unit_id());
			//当处理部门是客服部的时候
			if(UnitConstant.CUSTOMER_SERVICE.equals(dto.getCir_unit_id())){
				Object tmp_cir_id = baseDao.saveEntity(bCir_Bill);
				if(tmp_cir_id==null){
					return false;
				}
				//审核单信息
				BExamineBillEntity examine = new BExamineBillEntity();
				examine.setCir_id(tmp_cir_id.toString());
				examine.setAction_id(dto.getAction_bill_id());
				examine.setExamine_time(now);
				examine.setExamine_user_id(dto.getUserid());
				examine.setContent(dto.getContext());
				return baseDao.saveEntity(examine)!=null;
			}else{//当处理部门是其他部门的时候 b359246e-eb9b-4e0d-a830-51f3efecf9c4 768b2919-5d94-4f13-8919-196accb4127d
				bCir_Bill.setAction_end_time(dto.getEndTime());
				return baseDao.saveEntity(bCir_Bill)!=null;
			}
		}
		//当来源部门是其他部门时
		bCir_Bill.setCir_unit_id(UnitConstant.OFFICE);
		Object obj_cir_id = baseDao.saveEntity(bCir_Bill);
		if(obj_cir_id==null)
			return false;
		//更新投诉单状态
		String bill_id = dto.getBill_id();
		Finder finder = new Finder("update B_COM_BILL set active=1 where id=:id");
		finder.setParam("id", bill_id);
		if(!(baseDao.update(finder)>0)){
			return false;
		}
		//生成处理单
		BActionBillEntity actionBill = new BActionBillEntity();
		actionBill.setAction_time(now);
		actionBill.setAction_user_id(dto.getUserid());
		actionBill.setCir_id(obj_cir_id.toString());
		actionBill.setContent(dto.getContext());
		actionBill.setType(Integer.parseInt(dto.getOther_type()));
		return baseDao.saveEntity(actionBill)!=null;
	}
	//添加一个单据信息
	private boolean saveComBillByDto(BComBillDto dto, Date now)throws Exception{
		BComBillEntity bComBill = new BComBillEntity();
		bComBill.setActive(0);
		bComBill.setCmphone(dto.getPhone());
		bComBill.setContent(dto.getContext());
		bComBill.setCreate_time(now);
		bComBill.setCreate_user_id(dto.getUserid());
		bComBill.setCust_address(dto.getAddress());
		bComBill.setCustomer_name(dto.getCustName());
		bComBill.setReason(dto.getResons());
		bComBill.setType(0);
		Object obj_id = baseDao.saveEntity(bComBill);
		if(obj_id==null)
			return false;
		dto.setBill_id(obj_id.toString());
		return true;
	}
	//把一个流转单改为已办
	private boolean updateReadById(String cir_bill_id) throws Exception{
		if(StringUtils.isBlank(cir_bill_id))
			return false;
		Finder finder = new Finder("update B_CIR_BILL set ACTIVE=1 where ID=:id");
		finder.setParam("id", cir_bill_id);
		return baseDao.update(finder)>0;
	}
	public List<Map<String, Object>> findByDto(BComBillDto dto)
			throws Exception {
		Finder finder = new Finder("SELECT b.*,u.TRUE_NAME FROM B_COM_BILL b left join S_USER"
			+ " u on b.CREATE_USER_ID=u.ID where u.ACTIVE!=1");
		if(dto==null){
			return baseDao.queryForList(finder);
		}
		if(StringUtils.isNotBlank(dto.getId())){
			finder.append(" and b.ID=:ID");
			finder.setParam("ID", dto.getId());
		}
		finder.append(" order by b.CREATE_TIME desc");
		return baseDao.queryForList(finder, dto.getPage());
	}
	public List<Map<String, Object>> findoByDto(BComBillDto dto)
			throws Exception {
		Finder finder = new Finder("SELECT c.*,u.TRUE_NAME,un.UNIT_NAME as SRC_UNIT_NAME FROM B_CIR_BILL c left join S_USER u"
			+ " on c.active_user_id=u.ID left join S_UNITS un on c.src_unit_id=un.ID where u.ACTIVE!=1"
			+ " and un.ACTIVE!=1");
		if(dto==null){
			finder.append(" order by c.BILL_TIME desc");
			return baseDao.queryForList(finder);
		}
		if(dto.isDanbanis()){
			finder.append(" and c.ACTIVE=0");
		}else{
			finder.append(" and c.ACTIVE=1");
		}
		if(StringUtils.isNotBlank(dto.getUnitid())){
			if(dto.isDanbanis()){
				finder.append(" and c.CIR_UNIT_ID=:unitid");
			}else{
				finder.append(" and c.SRC_UNIT_ID=:unitid");
			}
			finder.setParam("unitid", dto.getUnitid());
		}
		finder.append(" order by c.BILL_TIME desc");
		return baseDao.queryForList(finder, dto.getPage());
	}
	//根据id得到一个单据信息
	private Map<String, Object> findComBillbyId(String comBillId)throws Exception{
		if(StringUtils.isBlank(comBillId)){
			return null;
		}
		BComBillDto dto = new BComBillDto();
		dto.setId(comBillId);
		List<Map<String, Object>> list = findByDto(dto);
		if(CollectionUtils.isEmpty(list))
			return null;
		return list.get(0);
	}
	//根据一个流转单id得到处理单信息
	private Map<String, Object> findActionBillByCirId(String cirBillId)throws Exception{
		if(StringUtils.isBlank(cirBillId))
			return null;
		Finder finder = new Finder("select * from B_ACTION_BILL where CIR_ID=:CIR_ID");
		finder.setParam("CIR_ID", cirBillId);
		List<Map<String, Object>> list = baseDao.queryForList(finder);
		if(CollectionUtils.isEmpty(list))
			return null;
		return list.get(0);
	}
	//根据流转单编号查询一个审核单信息
	public Map<String, Object> findExamineByCirid(String cir_id)throws Exception{
		if(StringUtils.isBlank(cir_id)){
			return null;
		}
		Finder finder = new Finder("SELECT * FROM B_EXAMINE_BILL where CIR_ID=:CIR_ID");
		finder.setParam("CIR_ID", cir_id);
		List<Map<String, Object>> list = baseDao.queryForList(finder);
		if(CollectionUtils.isEmpty(list))
			return null;
		return list.get(0);
	}
	public Map<String, Object> findCirInfoByDto(BComBillDto dto)
			throws Exception {
		//判断基本参数信息
		if(dto==null||StringUtils.isBlank(dto.getUnitid())||
			StringUtils.isBlank(dto.getId())||StringUtils.isBlank(
			dto.getSrc_unit_id())||StringUtils.isBlank(dto.getBill_id())){
			return null;
		}
		Map<String, Object> comBill = findComBillbyId(dto.getBill_id());
		if(comBill==null)
			return null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.putAll(comBill);
		map.put("COM_BILL_ID", dto.getBill_id());
		map.put("CIR_BILL_ID", dto.getId());
		//如果当前部门是办公室
		if(UnitConstant.OFFICE.equals(dto.getUnitid())){
			//如果来源部门是客服部则应该抓取的信息为
			if(UnitConstant.CUSTOMER_SERVICE.equals(dto.getSrc_unit_id())){
				map.put("srctype", ComBillSrcType.SRC_CUSTOMER);
				return map;
			}else{//如果来源部门为其他部门
				map.put("srctype", ComBillSrcType.SRC_OTHER);
				//处理部门名称
				SUnitsEntity unit = unitsService.findById(dto.getSrc_unit_id());
				map.put("UNIT_NAME", unit.getUnit_name());
				Map<String, Object> action_map = findActionBillByCirId(dto.getId());
				if(action_map==null)
					return null;
				Object obj_action_type = action_map.get("TYPE");
				if(obj_action_type==null)
					return null;
				String str_action_type = obj_action_type.toString();
				if("0".equals(str_action_type)){
					map.put("ACTION_TYPE", "已处理");
				}else{
					map.put("ACTION_TYPE", "驳回");
				}
				map.put("ACTION_CONTEXT", action_map.get("CONTENT"));
				map.put("ACTION_BILL_ID", map.get("ID"));
				return map;
			}
		}else if(UnitConstant.CUSTOMER_SERVICE.equals(dto.getUnitid())){
			map.put("srctype", ComBillSrcType.SRC_END);
			String cir_bill_id = dto.getId();
			Map<String, Object> exam = findExamineByCirid(cir_bill_id);
			if(exam==null){
				return null;
			}
			map.put("EXAM_ID", exam.get("ID"));
			map.put("EXAM_CONTENT", exam.get("CONTENT"));
			return map;
		}else{
			map.put("srctype", ComBillSrcType.SRC_OFFICE);
			return map;
		}
	}
	@Override
	public Map<String, Object> findLastUnitInfo(String billID)
			throws Exception {
		if(StringUtils.isBlank(billID))
			return null;
		Finder finder = new Finder("select c.*, s.UNIT_NAME from "
			+ "B_CIR_BILL as c left JOIN S_UNITS as s on c.CIR_UNIT_ID"
			+ "=s.ID where c.ACTIVE=0 and s.ACTIVE=0 and c.BILL_ID=:bill_id");
		finder.setParam("bill_id", billID);
		finder.append(" ORDER BY c.BILL_TIME DESC");
		List<Map<String, Object>> list = baseDao.queryForList(finder);
		if(CollectionUtils.isEmpty(list))
			return null;
		return list.get(0);
	}
}
